/**
 * 订单列表页面
 */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Form, Input, Button, Table, Modal, Select, message, Dropdown, Tabs } from 'antd';
import axios from 'axios';
import html2canvas from 'html2canvas';
import { Document, Packer, Paragraph, TextRun, Table as WordTable, TableRow, TableCell } from 'docx';
import { useTranslation } from '@/utils/i18n';

// 商品数据类型
interface Product {
  _id: string;
  shopname: string;
  price: number;
  nums: number;
  store: string;
}

// 订单数据类型 - 根据hsl copy.js模型定义
interface OrderData {
  _id: string;
  studentId: Product | string; // 兼容商品对象或ID字符串
  quantity: number;
  totalPrice: string;
  customerName: string;
  customerPhone: string;
  address: string;
  status: number | string;
  createdAt: string;
}

// 订单表单数据类型
interface OrderFormValues {
  studentId: string;
  quantity: number;
  customerName: string;
  customerPhone: string;
  address: string;
}

const API_BASE_URL =
  import.meta.env.VITE_ORDER_API_BASE_URL ||
  import.meta.env.VITE_API_BASE_URL ||
  'http://localhost:3000';

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

const generateMockProducts = (locale: string = 'zh-CN'): Product[] => {
  const isEnglish = locale === 'en-US';
  const stores = isEnglish ? ['Flagship Store', 'Experience Center', 'Direct Store', 'Authorized Store'] : ['旗舰店', '体验馆', '直营店', '授权店'];
  return Array.from({ length: 8 }, (_, idx) => ({
    _id: `MOCK_PROD_${idx + 1}`,
    shopname: isEnglish ? `Sample Product ${idx + 1}` : `示例商品 ${idx + 1}`,
    price: Number((Math.random() * 1500 + 99).toFixed(2)),
    nums: Math.floor(Math.random() * 200) + 10,
    store: stores[idx % stores.length]
  }));
};

const generateMockOrders = (productList: Product[] = [], locale: string = 'zh-CN'): OrderData[] => {
  const isEnglish = locale === 'en-US';
  const customerNames = isEnglish ? ['Alice', 'Bob', 'Charlie', 'Diana', 'Ethan'] : ['张三', '李四', '王五', '赵六', '钱七'];
  const addresses = isEnglish
    ? ['Pudong New District, Shanghai', 'Chaoyang District, Beijing', 'Xihu District, Hangzhou', 'Nanshan District, Shenzhen']
    : ['上海市浦东新区', '北京市朝阳区', '杭州市西湖区', '深圳市南山区'];

  return Array.from({ length: 10 }, (_, idx) => {
    const product = productList[idx % productList.length];
    const quantity = Math.floor(Math.random() * 3) + 1;
    const totalPrice = product ? (product.price * quantity).toFixed(2) : (199 * quantity).toFixed(2);
    const createdAt = new Date(Date.now() - idx * 3600 * 1000).toISOString();

    return {
      _id: `MOCK_ORDER_${idx + 1}`,
      studentId: product || {
        _id: `MOCK_PRODUCT_${idx + 1}`,
        shopname: isEnglish ? `Sample Product ${idx + 1}` : `示例商品 ${idx + 1}`,
        price: Number(totalPrice) / quantity,
        nums: 999,
        store: isEnglish ? 'Sample Store' : '示例门店'
      },
      quantity,
      totalPrice,
      customerName: customerNames[idx % customerNames.length],
      customerPhone: `138${Math.floor(Math.random() * 100000000)
        .toString()
        .padStart(8, '0')}`,
      address: addresses[idx % addresses.length],
      status: idx % 4 === 0 ? 0 : idx % 4 === 1 ? 1 : idx % 4 === 2 ? 2 : 3,
      createdAt
    } as OrderData;
  });
};

const getErrorMessage = (error: unknown, defaultMsg: string) => {
  const err = error as {
    message?: string;
    response?: { data?: { msg?: string; message?: string }; status?: number };
    config?: { url?: string };
  };
  return err.response?.data?.msg || err.response?.data?.message || err.message || defaultMsg;
};

const OrderList: React.FC = () => {
  const { t, locale } = useTranslation();
  const [form] = Form.useForm<OrderFormValues>();
  const [orders, setOrders] = useState<OrderData[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [activeTabKey, setActiveTabKey] = useState<string>('all');
  const hasShownNetworkErrorRef = useRef(false);
  const productsRef = useRef<Product[]>([]);

  // 根据当前选中的标签，获取要展示/导出的订单列表
  const getCurrentOrders = useCallback((): OrderData[] => {
    if (activeTabKey === 'pending') {
      return orders.filter(o => Number(o.status) === 0);
    }

    if (activeTabKey === 'shipped') {
      return orders.filter(o => Number(o.status) === 1);
    }

    if (activeTabKey === 'completed') {
      return orders.filter(o => Number(o.status) === 2);
    }

    // 默认返回全部订单
    return orders;
  }, [orders, activeTabKey]);

  // 获取商品列表
  const fetchProducts = useCallback(async () => {
    try {
      console.log('[订单列表] 开始请求商品数据...');
      const res = await apiClient.post('/hsl/product/list');
      console.log('[订单列表] 商品API响应:', res.data);
      if (res.data.code === 200) {
        const productData = res.data.data || [];
        setProducts(productData);
        productsRef.current = productData;
        console.log(`[订单列表] 成功加载 ${productData.length} 个商品`);
      } else {
        console.error('[订单列表] 商品API返回错误:', res.data);
        message.error(res.data.msg || t('order.list.messages.fetchProductsFailed'));
      }
    } catch (error: unknown) {
      console.error('获取商品列表失败:', error);
      const errorMsg = getErrorMessage(error, t('order.list.messages.fetchProductsFailed'));
      if (!hasShownNetworkErrorRef.current) {
        message.warning(t('order.list.messages.fetchProductsFallback', { message: errorMsg }));
        hasShownNetworkErrorRef.current = true;
      }
      const mockProducts = generateMockProducts(locale);
      setProducts(mockProducts);
      // 在后续订单生成时也能使用到模拟商品
      if (orders.length === 0) {
        setOrders(generateMockOrders(mockProducts, locale));
      }
    }
  }, [orders.length, locale, t]);

  // 获取订单列表
  const fetchOrders = useCallback(async () => {
    setIsLoading(true);
    try {
      console.log('[订单列表] 开始请求订单数据...');
      const res = await apiClient.get('/hsl/order/list');
      console.log('[订单列表] API响应:', res.data);
      if (res.data.code === 200) {
        // 直接设置数据，在表格渲染时处理状态显示
        setOrders(res.data.data);
      }
    } catch (error: unknown) {
      console.error('获取订单列表失败:', error);
      const errorMsg = getErrorMessage(error, t('order.list.messages.fetchOrdersFailed'));
      if (!hasShownNetworkErrorRef.current) {
        message.warning(t('order.list.messages.fetchOrdersFallback', { message: errorMsg }));
        hasShownNetworkErrorRef.current = true;
      }
      setOrders(generateMockOrders(products.length > 0 ? products : generateMockProducts(locale), locale));
    } finally {
      setIsLoading(false);
    }
  }, [products.length, locale, t]);

  // 添加订单 - 根据hsl.js API和hsl copy.js模型定义重写
  const handleAddOrder = async () => {
    try {
      // 表单验证
      const values = await form.validateFields();
      const quantity = Number(values.quantity);
      
      // 库存检查
      const product = products.find(p => p._id === values.studentId);
      if (product && product.nums < quantity) {
        message.error(t('order.list.messages.inventoryInsufficient', { stock: product.nums }));
        return;
      }
      
      // 显示操作提示
      // message.loading('正在创建订单...', 0);
      
      // 准备发送给后端的数据 - 严格按照hsl copy.js模型定义
      const orderData = {
        studentId: values.studentId, // 后端模型中使用studentId关联商品
        quantity: quantity,
        customerName: values.customerName,
        customerPhone: values.customerPhone,
        address: values.address,
        totalPrice: (product ? product.price * quantity : 0).toString(),
        status: 0, // 数值状态：0待处理
        createdAt: new Date().toISOString()
      };
      
      console.log('提交的订单数据:', orderData);
      const res = await apiClient.post('/hsl/order/create', orderData);
      
      if (res.data.code === 200) {
        message.success(t('order.list.messages.addSuccess'));
        setIsModalOpen(false);
        form.resetFields();
        fetchOrders(); // 刷新订单列表
      }
    } catch (error: unknown) {
      console.error('添加订单失败:', error);
      if (error instanceof Error) {
        message.error(error.message || t('order.list.messages.addFailed'));
      } else {
        message.error(t('order.list.messages.addFailedNetwork'));
      }
    }
  };

  // 更新订单状态
  const handleUpdateStatus = async (id: string, status: number) => {
    try {
      const res = await apiClient.put(`/hsl/order/update/${id}`, { status });
      if (res.data.code === 200) {
        message.success(t('order.list.messages.statusUpdateSuccess'));
        // 重新获取订单列表和商品列表，确保库存数据同步
        fetchOrders();
        fetchProducts();
      }
    } catch (error: unknown) {
      console.error('更新订单状态失败:', error);
      if (error instanceof Error) {
        message.error(error.message || t('order.list.messages.statusUpdateFailed'));
      } else {
        message.error(t('order.list.messages.statusUpdateFailedNetwork'));
      }
    }
  };

  // 导出为Excel (CSV格式)
  const exportToExcel = () => {
    setExportLoading(true);
    try {
      // 准备CSV数据
      const headers = [
        t('order.list.table.orderId'),
        t('order.list.table.productName'),
        t('order.list.table.productPrice'),
        t('order.list.table.quantity'),
        t('order.list.table.totalPrice'),
        t('order.list.table.customerName'),
        t('order.list.table.customerPhone'),
        t('order.list.table.address'),
        t('order.list.table.status'),
        t('order.list.table.createdAt')
      ];
      const rows = [headers];
      
      // 添加数据行
      getCurrentOrders().forEach(order => {
        const product = typeof order.studentId === 'object' ? order.studentId : null;
        rows.push([
          order._id,
          product?.shopname || t('order.list.messages.unknownProduct'),
          (product?.price || 0).toString(),
          order.quantity.toString(),
          order.totalPrice,
          order.customerName,
          order.customerPhone,
          order.address,
          order.status === 0
            ? t('order.list.status.pending')
            : order.status === 1
            ? t('order.list.status.shipped')
            : order.status === 2
            ? t('order.list.status.completed')
            : t('order.list.status.cancelled'),
          new Date(order.createdAt).toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN')
        ]);
      });
      
      // 生成CSV内容
      const csvContent = rows.map(row => 
        row.map(cell => `"${cell}"`).join(',')
      ).join('\n');
      
      // 创建下载链接
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${t('order.list.pageTitle')}_${new Date().toISOString().split('T')[0]}.xlsx`;
      link.click();
      
      message.success(t('order.list.messages.exportExcelSuccess'));
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error(t('order.list.messages.exportExcelFailed'));
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为图片
  const exportToImage = async () => {
    setExportLoading(true);
    try {
      // 创建一个临时的容器来渲染表格数据
      const tableContainer = document.createElement('div');
      tableContainer.style.width = '1200px';
      tableContainer.style.padding = '20px';
      tableContainer.style.backgroundColor = 'white';
      tableContainer.style.position = 'absolute';
      tableContainer.style.left = '-9999px';
      tableContainer.style.top = '-9999px';
      document.body.appendChild(tableContainer);

      // 添加标题
      const title = document.createElement('h2');
      title.textContent = t('order.list.pageTitle');
      title.style.textAlign = 'center';
      title.style.marginBottom = '20px';
      tableContainer.appendChild(title);

      // 添加生成时间
      const timeInfo = document.createElement('p');
      timeInfo.textContent = t('order.list.messages.generatedAt', {
        time: new Date().toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN'),
      });
      timeInfo.style.textAlign = 'center';
      timeInfo.style.marginBottom = '20px';
      tableContainer.appendChild(timeInfo);

      // 创建表格
      const table = document.createElement('table');
      table.style.width = '100%';
      table.style.borderCollapse = 'collapse';
      
      // 创建表头
      const thead = document.createElement('thead');
      const headerRow = document.createElement('tr');
      const headers = [
        t('order.list.table.orderId'),
        t('order.list.table.productName'),
        t('order.list.table.productPrice'),
        t('order.list.table.quantity'),
        t('order.list.table.totalPrice'),
        t('order.list.table.customerName'),
        t('order.list.table.customerPhone'),
        t('order.list.table.address'),
        t('order.list.table.status'),
        t('order.list.table.createdAt')
      ];
      headers.forEach(headerText => {
        const th = document.createElement('th');
        th.textContent = headerText;
        th.style.border = '1px solid #ddd';
        th.style.padding = '10px';
        th.style.backgroundColor = '#f5f5f5';
        th.style.fontWeight = 'bold';
        headerRow.appendChild(th);
      });
      thead.appendChild(headerRow);
      table.appendChild(thead);

      // 创建表格内容
      const tbody = document.createElement('tbody');
      getCurrentOrders().forEach(order => {
        const product = typeof order.studentId === 'object' ? order.studentId : null;
        const row = document.createElement('tr');
        const data = [
          order._id,
          product?.shopname || t('order.list.messages.unknownProduct'),
          `¥${product?.price || 0}`,
          order.quantity.toString(),
          `¥${order.totalPrice}`,
          order.customerName,
          order.customerPhone,
          order.address,
          order.status === 0
            ? t('order.list.status.pending')
            : order.status === 1
            ? t('order.list.status.shipped')
            : order.status === 2
            ? t('order.list.status.completed')
            : t('order.list.status.cancelled'),
          new Date(order.createdAt).toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN')
        ];
        data.forEach(cellText => {
          const td = document.createElement('td');
          td.textContent = cellText;
          td.style.border = '1px solid #ddd';
          td.style.padding = '10px';
          row.appendChild(td);
        });
        tbody.appendChild(row);
      });
      table.appendChild(tbody);
      tableContainer.appendChild(table);

      // 使用html2canvas截图
      const canvas = await html2canvas(tableContainer, {
        scale: 2, // 提高清晰度
        useCORS: true,
        backgroundColor: 'white'
      });

      // 转换为图片并下载
      const link = document.createElement('a');
      link.href = canvas.toDataURL('image/png');
      link.download = `${t('order.list.pageTitle')}_${new Date().toISOString().split('T')[0]}.png`;
      link.click();

      // 清理临时元素
      document.body.removeChild(tableContainer);
      message.success(t('order.list.messages.exportImageSuccess'));
    } catch (error) {
      console.error('导出图片失败:', error);
      message.error(t('order.list.messages.exportImageFailed'));
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为Word
  const exportToWord = async () => {
    setExportLoading(true);
    try {
      // 创建Word文档
      const doc = new Document({
        sections: [
          {
            properties: {},
            children: [
              // 添加标题
              new Paragraph({
                children: [
                  new TextRun({
                    text: t('order.list.pageTitle'),
                    bold: true,
                    size: 36,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 添加生成时间
              new Paragraph({
                children: [
                  new TextRun({
                    text: t('order.list.messages.generatedAt', {
                      time: new Date().toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN'),
                    }),
                    size: 20,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 创建表格
              new WordTable({
                rows: [
                  // 表头行
                  new TableRow({
                    children: [
                      new TableCell({
                        children: [new Paragraph(t('order.list.table.orderId'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.list.table.productName'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.list.table.productPrice'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.list.table.quantity'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.list.table.totalPrice'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.list.table.customerName'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                    ],
                  }),
                  // 数据行
                  ...getCurrentOrders().map(order => {
                    const product = typeof order.studentId === 'object' ? order.studentId : null;
                    return new TableRow({
                      children: [
                        new TableCell({
                          children: [new Paragraph(order._id)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(product?.shopname || t('order.list.messages.unknownProduct'))],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph((product?.price || 0).toString())],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(order.quantity.toString())],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(order.totalPrice)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(order.customerName)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                      ],
                    });
                  }),
                ],
              }),
            ],
          },
        ],
      });

      // 生成Word文件并下载
      const blob = await Packer.toBlob(doc);
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${t('order.list.pageTitle')}_${new Date().toISOString().split('T')[0]}.docx`;
      link.click();

      message.success(t('order.list.messages.exportWordSuccess'));
    } catch (error) {
      console.error('导出Word失败:', error);
      message.error(t('order.list.messages.exportWordFailed'));
    } finally {
      setExportLoading(false);
    }
  };

  // 删除订单
  const handleDeleteOrder = async (id: string) => {
    Modal.confirm({
      title: t('order.list.delete.confirmTitle'),
      content: t('order.list.delete.confirmContent'),
      okText: t('order.list.modal.ok'),
      cancelText: t('order.list.modal.cancel'),
      onOk: async () => {
        try {
          const res = await apiClient.delete(`/hsl/order/delete/${id}`);
          if (res.data.code === 200) {
            message.success(t('order.list.delete.success'));
            fetchOrders();
          }
        } catch (error) {
          console.error('删除订单失败:', error);
          message.error(t('order.list.delete.failed'));
        }
      }
    });
  };

  // 初始加载数据
  useEffect(() => {
    fetchProducts();
  }, [fetchProducts]);

  // 在商品加载完成后加载订单（只执行一次）
  const hasLoadedOrdersRef = useRef(false);
  useEffect(() => {
    if (!hasLoadedOrdersRef.current && (products.length > 0 || hasShownNetworkErrorRef.current)) {
      hasLoadedOrdersRef.current = true;
      fetchOrders();
    }
  }, [products.length, fetchOrders]);

  // 表格列配置
  const columns = [
    {
      title: t('order.list.table.orderId'),
      dataIndex: '_id',
      key: '_id',
      ellipsis: true
    },
    {
      title: t('order.list.table.productName'),
      dataIndex: ['studentId', 'shopname'],
      key: 'shopname',
      render: (text: string) => text || t('order.list.messages.unknownProduct')
    },
    {
      title: t('order.list.table.productPrice'),
      dataIndex: ['studentId', 'price'],
      key: 'price',
      render: (price: number) => `¥${price || 0}`
    },
    {
      title: t('order.list.table.quantity'),
      dataIndex: 'quantity',
      key: 'quantity'
    },
    {
      title: t('order.list.table.totalPrice'),
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      render: (price: string) => `¥${price}`
    },
    {
      title: t('order.list.table.customerName'),
      dataIndex: 'customerName',
      key: 'customerName'
    },
    {
      title: t('order.list.table.customerPhone'),
      dataIndex: 'customerPhone',
      key: 'customerPhone'
    },
    {
      title: t('order.list.table.address'),
      dataIndex: 'address',
      key: 'address',
      ellipsis: true
    },
    {
      title: t('order.list.table.status'),
      dataIndex: 'status',
      key: 'status',
      render: (status: number | string, record: OrderData) => (
        <Select 
          value={Number(status)} 
          style={{ width: 140 }}
          onChange={(newStatus: number) => handleUpdateStatus(record._id, newStatus)}
          options={[
            { label: t('order.list.status.pending'), value: 0 },
            { label: t('order.list.status.shipped'), value: 1 },
            { label: t('order.list.status.completed'), value: 2 },
            { label: t('order.list.status.cancelled'), value: 3 }
          ]}
        />
      )
    },
    {
      title: t('order.list.table.createdAt'),
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time: string) => new Date(time).toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN')
    },
    {
      title: t('order.list.table.actions'),
      key: 'action',
      render: (_: string, record: OrderData) => (
        <Button 
          danger 
          onClick={() => handleDeleteOrder(record._id)}
          disabled={Number(record.status) === 2}
        >
          {t('common.delete')}
        </Button>
      )
    }
  ];

  return (
    <div className="p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100 transition-colors">{t('order.list.pageTitle')}</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1 transition-colors">{t('order.list.pageDescription')}</p>
      </div>

      <div className="bg-white dark:bg-slate-900/80 rounded-lg shadow p-6 mb-6 transition-colors">
        <Button 
          type="primary" 
          onClick={() => setIsModalOpen(true)}
          className="mb-4"
        >
          {t('order.list.addOrder')}
        </Button>
        
        <Dropdown
          menu={{
            items: [
              {
                key: 'excel',
                label: t('order.list.exportExcel'),
                onClick: exportToExcel
              },
              {
                key: 'image',
                label: t('order.list.exportImage'),
                onClick: exportToImage
              },
              {
                key: 'word',
                label: t('order.list.exportWord'),
                onClick: exportToWord
              }
            ]
          }}
        >
          <Button
            type="default"
            disabled={isLoading || exportLoading || getCurrentOrders().length === 0}
            className="ml-4"
          >
            {exportLoading ? t('order.list.exporting') : t('order.list.exportData')}
          </Button>
        </Dropdown>
        
        <Tabs 
          activeKey={activeTabKey} 
          onChange={setActiveTabKey}
          className="mb-4"
        >
          <Tabs.TabPane tab={t('order.list.tabs.all')} key="all" />
          <Tabs.TabPane tab={t('order.list.tabs.pending')} key="pending" />
          <Tabs.TabPane tab={t('order.list.tabs.shipped')} key="shipped" />
          <Tabs.TabPane tab={t('order.list.tabs.completed')} key="completed" />
        </Tabs>

        <Table 
          columns={columns} 
          dataSource={getCurrentOrders()}
          loading={isLoading}
          rowKey="_id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => t('order.list.pagination', { total })
          }}
          locale={{
            emptyText: t('order.list.empty')
          }}
        />
      </div>

      {/* 添加订单模态框 */}
      <Modal
        title={t('order.list.modal.title')}
        open={isModalOpen}
        onOk={handleAddOrder}
        onCancel={() => {
          setIsModalOpen(false);
          form.resetFields();
        }}
        okText={t('order.list.modal.ok')}
        cancelText={t('order.list.modal.cancel')}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="studentId"
            label={t('order.list.modal.product')}
            rules={[{ required: true, message: t('order.list.modal.productPlaceholder') }]}
          >
            <Select placeholder={t('order.list.modal.productPlaceholder')}>
              {products.map(product => (
                <Select.Option key={product._id} value={product._id}>
                  {product.shopname} - ¥{product.price} ({t('order.list.modal.stock')}: {product.nums})
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="quantity"
            label={t('order.list.modal.quantity')}
            rules={[
              { required: true, message: t('order.list.modal.quantityRequired') },
              { validator: (_, value) => {
                  const numValue = Number(value);
                  if (isNaN(numValue) || numValue < 1) {
                    return Promise.reject(t('order.list.modal.quantityInvalid'));
                  }
                  return Promise.resolve();
                }}
            ]}
          >
            <Input type="number" min={1} placeholder={t('order.list.modal.quantityPlaceholder')} />
          </Form.Item>

          <Form.Item
            name="customerName"
            label={t('order.list.modal.customerName')}
            rules={[{ required: true, message: t('order.list.modal.customerNameRequired') }]}
          >
            <Input placeholder={t('order.list.modal.customerNamePlaceholder')} />
          </Form.Item>

          <Form.Item
            name="customerPhone"
            label={t('order.list.modal.customerPhone')}
            rules={[
              { required: true, message: t('order.list.modal.customerPhoneRequired') },
              { pattern: /^1[3-9]\d{9}$/, message: t('order.list.modal.customerPhoneInvalid') }
            ]}
          >
            <Input placeholder={t('order.list.modal.customerPhonePlaceholder')} />
          </Form.Item>

          <Form.Item
            name="address"
            label={t('order.list.modal.address')}
            rules={[{ required: true, message: t('order.list.modal.addressRequired') }]}
          >
            <Input.TextArea placeholder={t('order.list.modal.addressPlaceholder')} rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default OrderList;